package com.chookss.home.logContacts;


import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.base.StaticClass;
import com.chookss.home.entity.ContactEntity;
import com.chookss.home.entity.WatermarkEntity;
import com.chookss.mine.personal.PersonalHomeActivity;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyToast;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.PermissionUtils;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.CircleImageView;
import com.chookss.view.WaterMarkBg;
import com.google.gson.reflect.TypeToken;
import com.gyf.immersionbar.ImmersionBar;
import com.gyf.immersionbar.components.SimpleImmersionFragment;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.annotations.NonNull;
import scut.carson_ho.searchview.EditText_Clear;

@SuppressLint("ValidFragment")
public class ContactsBaseFragment extends SimpleImmersionFragment {

    public Activity mContext;
    Unbinder unbinder;
    @BindView(R.id.statusBar)
    View statusBar;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.title_back)
    LinearLayout title_back;
    @BindView(R.id.et_search)
    EditText_Clear etSearch;
    @BindView(R.id.tvCompany)
    TextView tvCompany;
    @BindView(R.id.rvView)
    RecyclerView rvView;
    @BindView(R.id.srlView)
    SmartRefreshLayout srlView;
    @BindView(R.id.llSearchEmpty)
    LinearLayout llSearchEmpty;
    @BindView(R.id.ivSearchEmpty)
    ImageView ivSearchEmpty;
    @BindView(R.id.ivWatermark)
    ImageView ivWatermark;
    @BindView(R.id.tvSearchEmpty)
    TextView tvSearchEmpty;
    @BindView(R.id.tv2SearchEmpty)
    TextView tv2SearchEmpty;
    @BindView(R.id.rlSearch)
    RelativeLayout rlSearch;
    private String key = "", companyNmae = "";//关键字、组织名、部门
    private ContactsAdapter adapter;
    private List<ContactEntity> list = new ArrayList<>();
    private String orgCode = "";
    private int currentPage = 1;
    private boolean isEnd = false;//是否到底
    private ArrayList<String> nameList = new ArrayList<>();//组织及部门排列
    private int type = 0; //0一级页面没有返回1是activity要返回
    private String phoneFlag="1";//0禁止通话1正常
    private String lpFlag = "";//0禁止1正常
    public ContactsBaseFragment() {

    }
    public ContactsBaseFragment(int type) {
        this.type = type;
    }
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = (Activity) context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_contacts_base, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    private void init() {
        NavigationTools.saveUseRecord(mContext,"1","07");
           lpFlag = new ShareUtils().getString(mContext, StaticClass.LP_FLAG, "1");
        //禁止截屏
        if ("0".equals(lpFlag)) {
            mContext.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
        }
        //顶部状态栏 处理
        phoneFlag=new ShareUtils().getString(mContext,StaticClass.PHONE_FLAG,"1");
        if (type == 0) {
            int statusBarHeight = Utils.getStatusBarHeight(mContext);
            RelativeLayout.LayoutParams topAllParams = (RelativeLayout.LayoutParams) statusBar.getLayoutParams();
            topAllParams.height = statusBarHeight;
            statusBar.setLayoutParams(topAllParams);
            statusBar.setBackgroundColor(mContext.getResources().getColor(R.color.white));
            statusBar.setVisibility(View.VISIBLE);
            title_back.setVisibility(View.GONE);
            tvTitle.getPaint().setFakeBoldText(true);
        } else {
            statusBar.setVisibility(View.GONE);
            title_back.setVisibility(View.VISIBLE);
        }
        WatermarkEntity watermarkEntity = NavigationTools.getWaterMark(this.getContext(), "15");
        if (watermarkEntity != null) {
            if ("1".equals(watermarkEntity.getStatusCd())) {
                WaterMarkBg.setWaterBg(this.getContext(), ivWatermark, new ShareUtils().getString(this.getContext(), StaticClass.USER_NICKNAME, "") + new ShareUtils().getString(this.getContext(), StaticClass.APPACCOUNT, ""), watermarkEntity.getCompanyWatermarkName(), true);

            }
        }

        companyNmae = new ShareUtils().getString(mContext, StaticClass.COMPANYNAME, "");
        if (Utils.isNull(companyNmae)) {
            companyNmae = getResources().getString(R.string.app_name);
        }
        nameList.add(companyNmae);
        tvCompany.setVisibility(View.VISIBLE);
        tvCompany.setText(companyNmae);
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {   // 按下完成按钮，这里和上面imeOptions对应
                    if (!Utils.isNull(v.getText().toString())) {
                        key = v.getText().toString();
                        etSearch.setText(key);
                        if(type==0){
                            //一级页面
                            Intent intent = new Intent(mContext, ContactsActivity.class);
                            intent.putExtra("key", v.getText().toString());
                            mContext.startActivity(intent);
                        }else{
                            tvCompany.setText(companyNmae);
                            tvCompany.setVisibility(View.VISIBLE);
                            srlView.autoRefresh();
                        }

                        return false;   //返回true，保留软键盘。false，隐藏软键盘
                    } else {
                        MyToast.show("请输入关键词");
                    }
                }
                return true;   //返回true，保留软键盘。false，隐藏软键盘
            }
        });

        rvView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        adapter = new ContactsAdapter(R.layout.item_contacts, list);
        rvView.setAdapter(adapter);
        srlView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getData();
                }
            }
        });
        srlView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                isEnd = false;
                currentPage = 1;
                getData();
            }
        });
        srlView.autoRefresh();
    }
    private void getData() {
        Map<String, String> map = new HashMap<>();
        String url = "";
        if (Utils.isNull(key)) {
            map.put("orgCode", orgCode);
            url = Urls.selectOrgAndEmpByCode;
        } else {
            map.put("searchParam", key);
            url = Urls.selectEmpByParam;
        }
        map.put("pageNum", currentPage + "");
        map.put("pageSize", "20");
//        if(Utils.isNull(source)){
//            //不需要权限，可以查看所有人
//            map.put("type", "0");
//        }else{
        //需要权限，只能查看下属的
        map.put("type", "1");
//        }

        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<ContactEntity>>>() {
        }.getType(), null, url, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<ContactEntity>>() {
            @Override
            public void onSuccess(List<ContactEntity> data) {
                loadEnd();
                if (currentPage == 1) {
                    list.clear();
                    adapter.notifyDataSetChanged();
                }
                if (llSearchEmpty == null||rvView==null) {
                    return;
                }
                if (data.size() == 0) {
                    isEnd = true;
                    if (list.size() == 0) {
                        rvView.setVisibility(View.GONE);
                        llSearchEmpty.setVisibility(View.VISIBLE);
                        if (Utils.isNull(key)) {
                            tvSearchEmpty.setText("暂无数据");
                            tv2SearchEmpty.setText("");
                        }else{
                            tvSearchEmpty.setText("搜索结果是空的");
                            tv2SearchEmpty.setText("换别的关键词试试吧");
                        }
                    }
                } else {
                    list.addAll(data);
                    rvView.setVisibility(View.VISIBLE);
                    llSearchEmpty.setVisibility(View.GONE);
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    class ContactsAdapter extends BaseQuickAdapter<ContactEntity, BaseViewHolderEx> {

        public ContactsAdapter(int layoutResId, List<ContactEntity> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolderEx helper, ContactEntity entity) {
            //组织
            LinearLayout llCompany = helper.getView(R.id.llCompany);
            TextView tvContactsName = helper.getView(R.id.tvContactsName);
            TextView tvContactsNum = helper.getView(R.id.tvContactsNum);
            //员工
            LinearLayout llEmployees = helper.getView(R.id.llEmployees);
            CircleImageView ivEmployees = helper.getView(R.id.ivEmployees);
            ImageView tvEmployeesPhone = helper.getView(R.id.tvEmployeesPhone);
            TextView tvEmployeesName = helper.getView(R.id.tvEmployeesName);
            TextView tvEmployeesJob = helper.getView(R.id.tvEmployeesJob);
            if("0".equals(phoneFlag)){
                tvEmployeesPhone.setAlpha(0.3f);
            }
            if ("0".equals(entity.getType())) {
                //部门
                llCompany.setVisibility(View.VISIBLE);
                llEmployees.setVisibility(View.GONE);
                tvContactsName.setText(entity.getEmployeeName());
                tvContactsNum.setText("(" + entity.getEmpNum() + ")");
            } else {
                //员工
                llCompany.setVisibility(View.GONE);
                llEmployees.setVisibility(View.VISIBLE);
                GlideUtils.loadAvatar(mContext, entity.getHeadPhotoThumbUrl(), ivEmployees);

                if (Utils.isNull(key)) {
                    tvEmployeesName.setText(entity.getEmployeeName());
                } else {
                    tvEmployeesName.setText(Utils.matcherSearchTitle(getResources().getColor(R.color.main_color), entity.getEmployeeName(), key));
                }
                tvEmployeesJob.setText(entity.getPost());
            }
            tvEmployeesPhone.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Urls.antiShake.check()) {
                        return;
                    }
                    if("1".equals(phoneFlag)){
                        toPhone(entity.getPhone());
                    }else{
                        MyToast.show("管理员已禁用拨打电话功能");
                    }
                }
            });
            ivEmployees.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Urls.antiShake.check()) {
                        return;
                    }
                    Intent intent = new Intent(mContext, PersonalHomeActivity.class);
                    intent.putExtra("employeeCode", entity.getEmployeeCode());
                    mContext.startActivity(intent);

                }
            });
            helper.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Urls.antiShake.check()) {
                        return;
                    }
                    if ("0".equals(entity.getType())) {
                        //是组织
                        Intent intent = new Intent(mContext, ContactsActivity.class);
                        intent.putExtra("orgCode", entity.getEmployeeCode());
                        intent.putExtra("companyNmae", companyNmae);
                        intent.putExtra("oldCompanyNmae", entity.getEmployeeName());
                        intent.putStringArrayListExtra("nameList", nameList);
                        intent.putExtra("department", entity.getEmployeeName());
                        mContext.startActivity(intent);
                    }
                }
            });
        }
    }



    private void toPhone(String phone) {
        if (!Utils.isNull(phone)) {
            XXPermissions.with(mContext)
                    .permission(Permission.CALL_PHONE)
                    .request(new OnPermissionCallback() {

                        @Override
                        public void onGranted(List<String> granted, boolean all) {
                            if (all) {
                                Intent callIntent = new Intent(Intent.ACTION_CALL,
                                        Uri.parse("tel:" + phone.replace("-", "")));
                                if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                                    return;
                                }
                                mContext.startActivity(callIntent);
                            } else {
                                PermissionUtils.errorSinglePermission(granted);
                            }
                        }

                        @Override
                        public void onDenied(List<String> denied, boolean quick) {
                            PermissionUtils.errorPermission(mContext, denied, quick);
                        }
                    });
        }
    }

    private void loadEnd() {
        if (null != srlView && srlView.getState() == RefreshState.Refreshing)
            srlView.finishRefresh(true);
        if (null != srlView && srlView.getState() == RefreshState.Loading)
            srlView.finishLoadMore(true);
    }
    @OnClick({R.id.title_back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                if(mContext!=null){
                    mContext.finish();
                }
                break;
        }

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void initImmersionBar() {
        ImmersionBar.with(getActivity())
                .transparentStatusBar()  /*透明状态栏，不写默认透明色*/  /*状态栏字体是深色，不写默认为亮色*/
                .statusBarDarkFont(true)
                .flymeOSStatusBarFontColor(R.color.grey_3)  /*修改flyme OS状态栏字体颜色*/
                .keyboardEnable(false).navigationBarEnable(false)
                .init();
    }
}
